//
//  SEGVisitorAccessViewModel.m
//  SEGViewModel
//
//  Created by 乔杨 on 2020/6/2.
//

#import "SEGVisitorAccessViewModel.h"
#import "SEGVisitorAccessManager.h"

#import "SEGVisitorAccessHistoryModel.h"
#import "SEGVisitorAccessDoorModel.h"
#import "SEGVisitorAccessCodeModel.h"

@implementation SEGVisitorAccessViewModel

- (instancetype)init {
    self = [super init];
    if (self) {
        // 默认可用次数一次
        self.selectedNumber = @"1";
        // 默认我的房间号
        SEGProfileHouselistModel *houseModel = [SEGProfileManager sharedManager].profile.houseList.firstObject;
        self.houseName = houseModel.houseName;
        self.houseId = houseModel.houseId;
    }
    return self;
}

- (void)seg_createPass {
    @weakify(self);
    self.passSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        NSString *custNameStr = [self.custNameStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        if (custNameStr.length == 0) {
            NSError *error = [NSError errorWithDomain:@"" code:0 userInfo:@{NSLocalizedFailureReasonErrorKey:kCustomerNamePlaceholder}];
            [subscriber sendError:error];
            return nil;
        }
        if (self.phoneStr.length == 0) {
            NSError *error = [NSError errorWithDomain:@"" code:0 userInfo:@{NSLocalizedFailureReasonErrorKey:kCustomerPhonePlaceholder}];
            [subscriber sendError:error];
            return nil;
        }
        if (self.phoneStr.length != kPhoneMaxLength) {
            NSError *error = [NSError errorWithDomain:@"" code:0 userInfo:@{NSLocalizedFailureReasonErrorKey:kPhoneError}];
            [subscriber sendError:error];
            return nil;
        }

        NSMutableDictionary *vistCusts = [NSMutableDictionary dictionaryWithDictionary:
                                          @{
                                            @"custName":custNameStr,
                                            @"tel":self.phoneStr,
                                            @"allowableNum":self.selectedNumber,
                                            }
                                          ];
        if (self.carNumberStr.length > 0) [vistCusts setObject:self.carNumberStr forKey:@"carNbr"];
        NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:
                                     @{
                                       @"channelId":@"2",//渠道ID，1是员工端，2业主端
                                       @"organId":kAccountCommunityID,
                                       @"userId":kAccountUserID,
                                       @"vistCusts":@[vistCusts],
                                       }
                                     ];
        [dict setObject:self.houseId forKey:@"houseId"];
        if (self.doorInfoDict) [dict setObject:self.doorInfoDict[@"doorIds"] forKey:@"doorsIds"];

        [[SEGVisitorAccessManager shareManager] requestSaveVisitCustomListWithDict:dict finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            if (isSuccessed) {
                //积分行为设置
                [[SEGAnalyseBehaviorManager sharedManager] requestIntegralGrowthWithCode:SEGIntegralCode.visitor finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                }];
                [subscriber sendNext:nil];
                [subscriber sendCompleted];
                
            } else {
                NSError *error = [NSError errorWithDomain:@"" code:0 userInfo:@{NSLocalizedFailureReasonErrorKey:errorMessage}];
                [subscriber sendError:error];
            }
        }];
        return nil;
        }];
}
- (void)seg_sharePass {
    self.shareCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(NSString *vistLogid) {
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            [[SEGVisitorAccessManager shareManager] requestShareVisitorPassportWithVistLogid:vistLogid finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                if (isSuccessed) {
                    if([[SEGVisitorAccessManager shareManager].codeModel.isValid isEqualToString:@"0"]) {
                        [subscriber sendNext:nil];
                        [subscriber sendCompleted];
                    } else {
                        NSError *error = [NSError errorWithDomain:@"" code:1 userInfo:@{NSLocalizedFailureReasonErrorKey:@"访客通行证已失效，请重新申请"}];
                        [subscriber sendError:error];
                    }
                } else {
                    NSError *error = [NSError errorWithDomain:@"" code:2 userInfo:@{NSLocalizedFailureReasonErrorKey:errorMessage}];
                    [subscriber sendError:error];
                }
            }];
            return nil;
        }];
    }];
}
- (void)seg_bindDataWithModel:(SEGVisitorAccessHistoryModel *)bindModel {
    if (!bindModel) return;
    // 访客姓名
    self.custNameStr = bindModel.visitorName;
    // 访客电话
    self.phoneStr = bindModel.visitorTel;
    // 车牌号
    self.carNumberStr = bindModel.visitorCarCode;
   
    // 我的房间号
    [[SEGProfileManager sharedManager].profile.houseList enumerateObjectsUsingBlock:^(SEGProfileHouselistModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (self.houseId.integerValue == obj.houseId.integerValue) {
            self.houseName = obj.houseName;
            self.houseId = obj.houseId;
            *stop = YES;
        }
    }];
    // 可用次数
    self.selectedNumber = bindModel.allowableNum;
    // 授权门禁
    NSMutableArray *doorNames = [NSMutableArray array];
    [bindModel.visitorDoors enumerateObjectsUsingBlock:^(SEGVisitorAccessDoorModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [doorNames addObject:obj.doorName];
    }];
    NSString *doorString = [doorNames componentsJoinedByString:@","];
    if (doorString.length > 0) self.doorInfoDict = @{@"doorNames":doorString};
 }

@end
